// UI系统 - 管理所有用户界面
class UISystem {
    constructor(scene) {
        this.scene = scene;
    }

    createGameUI() {
        // UI文本 - 使用固定坐标，不跟随世界移动
        const leftPadding = 16;  // 左边距
        let currentY = 16;       // 起始Y坐标
        const lineSpacing = 28;  // 行间距

        // 清理可能存在的旧UI元素
        this.cleanupGameUI();

        // 波次文本
        this.scene.waveText = this.scene.add.text(leftPadding, currentY, `波次: ${this.scene.wave}`, {
            fontSize: '16px',
            fill: '#ffffff'
        }).setScrollFactor(0).setDepth(1000);
        currentY += lineSpacing;

        // 波数倒计时文本
        this.scene.waveCountdownText = this.scene.add.text(leftPadding, currentY, '', {
            fontSize: '16px',
            fill: '#00ff00',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 1
        }).setScrollFactor(0).setDepth(1000);
        currentY += lineSpacing;

        // 生命值文本
        this.scene.healthText = this.scene.add.text(leftPadding, currentY, `生命: ${this.scene.playerStats.health}`, {
            fontSize: '16px',
            fill: '#ffffff'
        }).setScrollFactor(0).setDepth(1000);
        currentY += lineSpacing;

        // 武器信息显示
        this.scene.weaponText = this.scene.add.text(leftPadding, currentY, `武器: ${this.scene.weapons.join(', ')}`, {
            fontSize: '16px',
            fill: '#ffffff'
        }).setScrollFactor(0).setDepth(1000);
        currentY += lineSpacing;

        // 经验值显示
        this.scene.expText = this.scene.add.text(leftPadding, currentY, `等级: ${this.scene.playerLevel} (${this.scene.experiencePoints}/${this.scene.expToNextLevel})`, {
            fontSize: '16px',
            fill: '#00ffff'
        }).setScrollFactor(0).setDepth(1000);
        currentY += lineSpacing;

        // 金币显示
        this.scene.coinText = this.scene.add.text(leftPadding, currentY, `金币: ${this.scene.gold || 0}`, {
            fontSize: '18px',
            fill: '#FFD700',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 2
        }).setScrollFactor(0).setDepth(1000);

        // 经验条 - 固定在屏幕底部，使用相对位置
        const gameWidth = this.scene.game.config.width;
        const gameHeight = this.scene.game.config.height;

        this.scene.expBarBg = this.scene.add.rectangle(gameWidth / 2, gameHeight - 20, gameWidth * 0.8, 10, 0x333333)
            .setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(1000);

        this.scene.expBar = this.scene.add.rectangle(gameWidth / 2, gameHeight - 20, gameWidth * 0.8, 8, 0x00ffff)
            .setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(1001);
        this.scene.expBar.scaleX = 0;

        // 暂停提示 - 只在PC端显示
        if (!GameConfig.isMobile()) {
            this.scene.pauseHintText = this.scene.add.text(10, gameHeight - 50, '按 ESC 暂停游戏', {
                fontSize: '14px',
                fill: '#888888',
                alpha: 0.7
            }).setScrollFactor(0).setDepth(1000);
        }

        // 创建Boss UI元素（初始隐藏）
        this.createBossUI();

        // 创建Boss指示器（初始隐藏）
        this.createBossIndicator();

        // 角色属性面板相关
        this.characterStatsPanel = null;
        this.characterStatsElements = [];
    }

    // 清理游戏UI元素
    cleanupGameUI() {
        const uiElements = [
            'waveText',
            'waveCountdownText',
            'healthText',
            'weaponText',
            'expText',
            'coinText',
            'expBarBg',
            'expBar'
        ];

        uiElements.forEach(elementName => {
            if (this.scene[elementName]) {
                this.scene[elementName].destroy();
                this.scene[elementName] = null;
            }
        });
    }

    // 更新波次文本
    updateWaveText() {
        if (this.scene.waveText) {
            this.scene.waveText.setText(`波次: ${this.scene.wave}`);
        }
    }

    createBossUI() {
        // Boss血条 - 屏幕顶部，固定在视口中
        this.bossHealthBg = this.scene.add.rectangle(400, 30, 500, 20, 0x333333)
            .setScrollFactor(0)
            .setDepth(9999);
        this.bossHealthBg.setStrokeStyle(2, 0xffffff);

        this.bossHealthFg = this.scene.add.rectangle(400, 30, 500, 16, 0xff0000)
            .setScrollFactor(0)
            .setDepth(9999);

        // Boss名称
        this.bossText = this.scene.add.text(400, 50, `Boss`, {
            fontSize: '16px',
            fill: '#ffffff',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 2
        }).setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(9999);

        // 初始隐藏
        this.bossHealthBg.setVisible(false);
        this.bossHealthFg.setVisible(false);
        this.bossText.setVisible(false);
    }

    createBossIndicator() {
        // 创建三角形指示器
        const indicatorGraphics = this.scene.add.graphics();
        indicatorGraphics.fillStyle(0xff0000, 1);
        indicatorGraphics.lineStyle(2, 0xffffff, 1);
        indicatorGraphics.beginPath();
        indicatorGraphics.moveTo(0, -15);
        indicatorGraphics.lineTo(10, 5);
        indicatorGraphics.lineTo(-10, 5);
        indicatorGraphics.closePath();
        indicatorGraphics.fillPath();
        indicatorGraphics.strokePath();

        // 将图形转换为纹理
        indicatorGraphics.generateTexture('boss_indicator', 20, 20);
        indicatorGraphics.destroy();

        // 创建指示器精灵
        this.bossIndicator = this.scene.add.sprite(0, 0, 'boss_indicator')
            .setScrollFactor(0)
            .setDepth(9999);

        // 添加闪烁动画
        this.scene.tweens.add({
            targets: this.bossIndicator,
            alpha: 0.5,
            duration: 500,
            yoyo: true,
            repeat: -1
        });

        // 添加距离文本
        this.bossDistanceText = this.scene.add.text(0, 0, '', {
            fontSize: '12px',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 2
        }).setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(9999);

        // 初始隐藏
        this.bossIndicator.setVisible(false);
        this.bossDistanceText.setVisible(false);
    }

    showUpgradeMenu(upgradeOptions) {
        // 清理可能存在的旧UI
        this.closeUpgradeMenu();

        this.scene.isUpgrading = true;
        this.scene.physics.pause();

        // 确保玩家停止移动
        if (this.scene.player) {
            this.scene.player.setVelocity(0, 0);
        }

        // 获取屏幕中心位置（相对于摄像机视野）
        const camera = this.scene.cameras.main;
        const centerX = camera.width / 2;
        const centerY = camera.height / 2;

        // 创建升级背景 - 固定在摄像机视野中
        const upgradeBg = this.scene.add.rectangle(centerX, centerY, camera.width, camera.height, 0x000000, 0.8)
            .setScrollFactor(0)
            .setDepth(2000)
            .setInteractive()
            .on('pointerdown', function (pointer) {
                pointer.event.stopPropagation(); // 阻止点击穿透
            });

        // 升级标题
        const title = this.scene.add.text(centerX, centerY - 100, '选择升级', {
            fontSize: '32px',
            fill: '#ffffff'
        }).setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(2001);

        // 存储UI元素用于清理
        this.upgradeElements = [upgradeBg, title];

        // 创建升级选项按钮
        upgradeOptions.forEach((option, index) => {
            const y = centerY - 50 + (index * 80);

            // 创建一个容器来包装按钮和文本
            const container = this.scene.add.container(centerX, y).setDepth(2001).setScrollFactor(0);

            // 根据稀有度设置颜色
            const rarityColors = {
                'common': 0x95a5a6,      // 灰色
                'uncommon': 0x2ecc71,    // 绿色
                'rare': 0x3498db,        // 蓝色
                'epic': 0x9b59b6,        // 紫色
                'legendary': 0xf39c12     // 橙色
            };
            const bgColor = rarityColors[option.rarity] || 0x34495e;

            // 选项背景
            const optionBg = this.scene.add.rectangle(0, 0, 500, 60, bgColor)
                .setStrokeStyle(2, 0xffffff)
                .setAlpha(0.8);

            // 选项文本
            const optionText = this.scene.add.text(0, 0, `${option.name}\n${option.description}`, {
                fontSize: '16px',
                fill: '#ffffff',
                align: 'center',
                fontStyle: option.rarity === 'legendary' ? 'bold' : 'normal'
            }).setOrigin(0.5);

            // 稀有度标识
            const rarityText = this.scene.add.text(-230, -20, option.rarity.toUpperCase(), {
                fontSize: '10px',
                fill: '#ffffff',
                fontStyle: 'bold'
            });

            // 将背景和文本添加到容器
            container.add([optionBg, optionText, rarityText]);

            // 使整个容器可交互
            container.setSize(500, 60);
            container.setInteractive({ useHandCursor: true })
                .on('pointerover', () => {
                    optionBg.setAlpha(1.0);
                    container.setScale(1.05);
                })
                .on('pointerout', () => {
                    optionBg.setAlpha(0.8);
                    container.setScale(1.0);
                })
                .on('pointerdown', () => {
                    if (!this.scene.isUpgrading) return;

                    // 执行升级效果
                    option.effect();

                    // 关闭升级菜单
                    this.closeUpgradeMenu();
                });

            // 添加到清理列表
            this.upgradeElements.push(container);
        });

        // 添加刷新按钮
        if (this.scene.upgradeSystem) {
            const refreshInfo = this.scene.upgradeSystem.getRefreshButtonInfo();
            const refreshY = centerY + 200;

            // 刷新按钮容器
            const refreshContainer = this.scene.add.container(centerX, refreshY).setDepth(2001).setScrollFactor(0);

            // 刷新按钮背景
            const refreshBg = this.scene.add.rectangle(0, 0, 200, 40, refreshInfo.canAfford ? 0xf39c12 : 0x7f8c8d)
                .setStrokeStyle(2, 0xffffff);

            // 刷新按钮文本
            const refreshText = this.scene.add.text(0, 0, refreshInfo.text, {
                fontSize: '14px',
                fill: '#ffffff',
                fontStyle: 'bold'
            }).setOrigin(0.5);

            refreshContainer.add([refreshBg, refreshText]);

            // 只有金币足够时才可交互
            if (refreshInfo.canAfford) {
                refreshContainer.setSize(200, 40);
                refreshContainer.setInteractive({ useHandCursor: true })
                    .on('pointerover', () => {
                        refreshBg.setFillStyle(0xe67e22);
                        refreshContainer.setScale(1.05);
                    })
                    .on('pointerout', () => {
                        refreshBg.setFillStyle(0xf39c12);
                        refreshContainer.setScale(1.0);
                    })
                    .on('pointerdown', () => {
                        if (!this.scene.isUpgrading) return;

                        // 刷新升级选项
                        const newOptions = this.scene.upgradeSystem.refreshUpgrades();
                        if (newOptions) {
                            this.showUpgradeMenu(newOptions);
                        }
                    });
            }

            this.upgradeElements.push(refreshContainer);
        }
    }

    showBossRewardMenu(bossRewards) {
        this.scene.isUpgrading = true;
        this.scene.physics.pause();

        // 确保玩家停止移动
        if (this.scene.player) {
            this.scene.player.setVelocity(0, 0);
        }

        // 获取屏幕中心位置（相对于摄像机视野）
        const camera = this.scene.cameras.main;
        const centerX = camera.width / 2;
        const centerY = camera.height / 2;

        // 创建升级背景 - 固定在摄像机视野中
        const upgradeBg = this.scene.add.rectangle(centerX, centerY, camera.width, camera.height, 0x000000, 0.9)
            .setScrollFactor(0)
            .setDepth(2000);

        // Boss击败标题
        const title = this.scene.add.text(centerX, centerY - 120, 'Boss击败!', {
            fontSize: '36px',
            fill: '#ffff00'
        }).setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(2001);

        const subtitle = this.scene.add.text(centerX, centerY - 80, '选择特殊奖励', {
            fontSize: '24px',
            fill: '#ffffff'
        }).setOrigin(0.5)
            .setScrollFactor(0)
            .setDepth(2001);

        // 存储UI元素用于清理
        this.bossRewardElements = [upgradeBg, title, subtitle];

        // 创建奖励选项按钮
        bossRewards.forEach((reward, index) => {
            const y = centerY - 30 + (index * 90);

            // 选项背景 (金色边框)
            const optionBg = this.scene.add.rectangle(centerX, y, 550, 70, 0x2c3e50)
                .setStrokeStyle(3, 0xffd700)
                .setScrollFactor(0)
                .setDepth(2001);

            // 选项文本
            const optionText = this.scene.add.text(centerX, y, `${reward.name}\n${reward.description}`, {
                fontSize: '18px',
                fill: '#ffffff',
                align: 'center'
            }).setOrigin(0.5)
                .setScrollFactor(0)
                .setDepth(2002);

            // 添加到清理列表
            this.bossRewardElements.push(optionBg, optionText);

            // 点击事件
            optionBg.setInteractive();
            optionBg.on('pointerdown', () => {
                reward.effect();
                this.closeBossRewardMenu();
            });

            // 悬停效果 (金色高亮)
            optionBg.on('pointerover', () => {
                optionBg.setFillStyle(0x3a4a5a);
            });

            optionBg.on('pointerout', () => {
                optionBg.setFillStyle(0x2c3e50);
            });
        });
    }

    showGameOver(stats) {
        // 获取屏幕中心位置（相对于摄像机视野）
        const camera = this.scene.cameras.main;
        const centerX = camera.width / 2;
        const centerY = camera.height / 2;

        // 创建半透明黑色背景
        const gameOverBg = this.scene.add.rectangle(centerX, centerY, camera.width, camera.height, 0x000000, 0.8)
            .setScrollFactor(0)
            .setDepth(3000);

        // 游戏结束标题
        const title = this.scene.add.text(centerX, centerY - 150, '游戏结束', {
            fontSize: '48px',
            fill: '#ff0000',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 4
        }).setOrigin(0.5).setScrollFactor(0).setDepth(3001);

        // 统计信息
        const statsText = this.scene.add.text(centerX, centerY - 50,
            `存活波次: ${stats.wave}\n` +
            `击杀敌人: ${stats.enemiesKilled}\n` +
            `击杀Boss: ${stats.bossesKilled}\n` +
            `获得经验: ${stats.experiencePoints}\n` +
            `获得金币: ${stats.gold}`, {
            fontSize: '24px',
            fill: '#ffffff',
            align: 'center'
        }).setOrigin(0.5).setScrollFactor(0).setDepth(3001);

        // 返回菜单按钮
        const menuButton = this.scene.add.rectangle(centerX, centerY + 100, 200, 50, 0x3498db)
            .setScrollFactor(0)
            .setDepth(3001)
            .setInteractive({ useHandCursor: true });

        const menuText = this.scene.add.text(centerX, centerY + 100, '返回菜单', {
            fontSize: '24px',
            fill: '#ffffff'
        }).setOrigin(0.5).setScrollFactor(0).setDepth(3002);

        // 按钮交互效果
        menuButton.on('pointerover', () => {
            menuButton.setFillStyle(0x2980b9);
        });

        menuButton.on('pointerout', () => {
            menuButton.setFillStyle(0x3498db);
        });

        menuButton.on('pointerdown', () => {
            // 切换回主菜单场景
            this.scene.scene.start('MainMenu');
        });
    }

    resumeGame() {
        this.scene.isUpgrading = false;
        this.scene.physics.resume();
    }

    closeUpgradeMenu() {
        if (this.upgradeElements) {
            this.upgradeElements.forEach(element => {
                if (element) {
                    if (element.removeAllListeners) {
                        element.removeAllListeners();
                    }
                    if (element.destroy) {
                        element.destroy();
                    }
                }
            });
            this.upgradeElements = [];
        }

        // 恢复游戏 - 检查是否有其他暂停状态
        if (this.scene) {
            // 只有在没有其他暂停状态时才恢复游戏
            if (!this.scene.isShopOpen && !this.scene.isManuallyPaused) {
                this.scene.isUpgrading = false;
                if (this.scene.physics) {
                    this.scene.physics.resume();
                    console.log('升级菜单关闭，物理引擎已恢复');
                }

                // 恢复计时器
                if (this.scene.spawnEnemyTimer && this.scene.spawnEnemyTimer.paused && !this.scene.isBossWave) {
                    this.scene.spawnEnemyTimer.paused = false;
                    console.log('升级菜单关闭，敌人生成计时器已恢复');
                }

                if (this.scene.waveTimer && this.scene.waveTimer.paused) {
                    this.scene.waveTimer.paused = false;
                    console.log('升级菜单关闭，波次计时器已恢复');
                }

                if (this.scene.countdownTimer && this.scene.countdownTimer.paused) {
                    this.scene.countdownTimer.paused = false;
                    console.log('升级菜单关闭，倒计时计时器已恢复');
                }

                console.log('升级菜单关闭，游戏完全恢复');
            }
            // 如果有其他暂停状态，保持暂停
            else {
                this.scene.isUpgrading = false; // 升级状态结束
                console.log('升级菜单关闭，但游戏仍有其他暂停状态 - isShopOpen:', this.scene.isShopOpen, 'isManuallyPaused:', this.scene.isManuallyPaused);
            }
        }
    }

    closeBossRewardMenu() {
        if (this.bossRewardElements) {
            this.bossRewardElements.forEach(element => {
                if (element && element.destroy) {
                    element.destroy();
                }
            });
            this.bossRewardElements = [];
        }

        // 恢复游戏 - 检查是否有其他暂停状态
        if (this.scene) {
            // 只有在没有其他暂停状态时才恢复游戏
            if (!this.scene.isShopOpen && !this.scene.isManuallyPaused) {
                this.scene.isUpgrading = false;
                if (this.scene.physics) {
                    this.scene.physics.resume();
                    console.log('升级选择完成，物理引擎已恢复');
                }

                // 恢复计时器
                if (this.scene.spawnEnemyTimer && this.scene.spawnEnemyTimer.paused && !this.scene.isBossWave) {
                    this.scene.spawnEnemyTimer.paused = false;
                    console.log('升级选择完成，敌人生成计时器已恢复');
                }

                if (this.scene.waveTimer && this.scene.waveTimer.paused) {
                    this.scene.waveTimer.paused = false;
                    console.log('升级选择完成，波次计时器已恢复');
                }

                if (this.scene.countdownTimer && this.scene.countdownTimer.paused) {
                    this.scene.countdownTimer.paused = false;
                    console.log('升级选择完成，倒计时计时器已恢复');
                }

                console.log('升级选择完成，游戏完全恢复');
            }
            // 如果有其他暂停状态，保持暂停
            else {
                this.scene.isUpgrading = false; // 升级状态结束
                console.log('升级选择完成，但游戏仍有其他暂停状态 - isShopOpen:', this.scene.isShopOpen, 'isManuallyPaused:', this.scene.isManuallyPaused);
            }
        }
    }

    // 更新Boss血条
    updateBossUI(boss, wave) {
        if (boss && boss.active) {
            // 显示Boss UI
            this.bossHealthBg.setVisible(true);
            this.bossHealthFg.setVisible(true);
            this.bossText.setVisible(true);

            // 更新Boss名称 - 确保wave参数有效
            const displayWave = wave || boss.wave || this.scene.wave || 5;
            this.bossText.setText(`Boss - 波次 ${displayWave}`);

            // 更新血条 - 添加安全检查
            if (boss.maxHealth > 0) {
                const healthPercent = Math.max(0, boss.health / boss.maxHealth);
                this.bossHealthFg.scaleX = healthPercent;
            }
        } else {
            // 隐藏Boss UI
            this.bossHealthBg.setVisible(false);
            this.bossHealthFg.setVisible(false);
            this.bossText.setVisible(false);
        }
    }

    // 更新Boss指示器
    updateBossIndicator(boss) {
        if (!boss) {
            this.bossIndicator.setVisible(false);
            this.bossDistanceText.setVisible(false);
            return;
        }

        // 获取相机和游戏尺寸
        const camera = this.scene.cameras.main;
        const gameWidth = this.scene.game.config.width;
        const gameHeight = this.scene.game.config.height;

        // 计算Boss相对于相机的位置
        const bossCamX = boss.x - camera.scrollX;
        const bossCamY = boss.y - camera.scrollY;

        // 检查Boss是否在视口内
        const inView = (
            bossCamX > 0 &&
            bossCamX < gameWidth &&
            bossCamY > 0 &&
            bossCamY < gameHeight
        );

        // 如果Boss不在视口内，显示指示器
        if (!inView) {
            // 计算指示器位置
            const angle = Phaser.Math.Angle.Between(
                camera.scrollX + gameWidth / 2,
                camera.scrollY + gameHeight / 2,
                boss.x, boss.y
            );

            // 计算指示器在屏幕边缘的位置
            const padding = 40; // 距离屏幕边缘的距离
            let indicatorX = gameWidth / 2 + Math.cos(angle) * (gameWidth / 2 - padding);
            let indicatorY = gameHeight / 2 + Math.sin(angle) * (gameHeight / 2 - padding);

            // 设置指示器位置和旋转
            this.bossIndicator.setPosition(indicatorX, indicatorY);
            this.bossIndicator.setRotation(angle + Math.PI / 2); // 让箭头指向Boss
            this.bossIndicator.setVisible(true);

            // 计算并显示距离
            const distance = Math.floor(Phaser.Math.Distance.Between(
                this.scene.player.x, this.scene.player.y,
                boss.x, boss.y
            ));
            this.bossDistanceText.setText(`${distance}m`);
            this.bossDistanceText.setPosition(indicatorX, indicatorY + 20);
            this.bossDistanceText.setVisible(true);
        } else {
            // 如果Boss在视口内，隐藏指示器
            this.bossIndicator.setVisible(false);
            this.bossDistanceText.setVisible(false);
        }
    }

    // 更新经验值显示
    updateExpText() {
        if (this.scene.expText) {
            this.scene.expText.setText(`等级: ${this.scene.playerLevel} (${this.scene.experiencePoints}/${this.scene.expToNextLevel})`);
        }
    }

    updateHealthText(health) {
        if (this.scene.healthText) {
            this.scene.healthText.setText(`生命: ${health}`);
        }
    }

    updateCoinText(coins) {
        if (this.scene.coinText) {
            this.scene.coinText.setText(`金币: ${coins}`);
        }
    }

    // 更新所有UI元素
    updateAllUI() {
        // 更新基础信息
        this.updateWaveText();
        this.updateExpText();
        this.updateHealthText(this.scene.playerStats.health);
        this.updateCoinText(this.scene.gold);
        
        // 更新武器显示
        if (this.scene.weaponText) {
            this.scene.weaponText.setText(`武器: ${this.scene.weapons.join(', ')}`);
        }
        
        // 更新经验条
        if (this.scene.expBar) {
            const expProgress = this.scene.expToNextLevel > 0 ? 
                this.scene.experiencePoints / this.scene.expToNextLevel : 0;
            this.scene.expBar.scaleX = Math.min(1, expProgress);
        }
        
        // 如果属性面板打开，刷新属性面板
        if (this.characterStatsPanel) {
            this.hideCharacterStats();
            this.showCharacterStats();
        }
    }

    // 更新法力值显示
    updateManaText(mana, maxMana) {
        // 如果需要显示法力值，可以在这里添加
        if (this.scene.manaText) {
            this.scene.manaText.setText(`法力: ${mana} / ${maxMana}`);
        }
    }

    // 更新能量值显示
    updateEnergyText(energy, maxEnergy) {
        // 如果需要显示能量值，可以在这里添加
        if (this.scene.energyText) {
            this.scene.energyText.setText(`能量: ${energy} / ${maxEnergy}`);
        }
    }

    // 显示角色属性面板
    showCharacterStats() {
        if (this.characterStatsPanel) {
            return; // 已经显示了
        }

        const camera = this.scene.cameras.main;
        const centerX = camera.width / 2;
        const centerY = camera.height / 2;

        // 检测是否为移动端
        const isMobile = GameConfig.isMobile();
        const panelWidth = isMobile ? camera.width * 0.95 : camera.width * 0.9;
        const panelHeight = isMobile ? camera.height * 0.95 : camera.height * 0.9;

        // 创建半透明背景
        const background = this.scene.add.rectangle(centerX, centerY, panelWidth, panelHeight, 0x000000, 0.9)
            .setScrollFactor(0)
            .setDepth(2000);

        // 标题 - 移动端适配字体大小
        const titleFontSize = isMobile ? '20px' : '28px';
        const title = this.scene.add.text(centerX, centerY - panelHeight / 2 + 30, '角色属性', {
            fontSize: titleFontSize,
            fill: '#ffffff',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 2
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2001);

        // 获取角色数据
        const stats = this.scene.playerStats;
        const gameStats = {
            wave: this.scene.wave,
            level: this.scene.playerLevel,
            exp: this.scene.experiencePoints,
            expToNext: this.scene.expToNextLevel,
            gold: this.scene.gold,
            enemiesKilled: this.scene.enemiesKilled,
            bossesKilled: this.scene.bossesKilled,
            gameTime: Math.floor(this.scene.gameTime / 1000),
            upgradeCount: this.scene.upgradeSystem ? this.scene.upgradeSystem.upgradeCount || 0 : 0
        };

        // 创建滚动视图
        const scrollY = centerY - panelHeight / 2 + 70;
        const lineHeight = isMobile ? 16 : 20;
        const fontSize = isMobile ? '10px' : '14px';
        const sectionSpacing = isMobile ? 25 : 35;

        let currentY = scrollY;

        // 创建分类显示函数
        const createSection = (title, items, color = '#ffffff') => {
            // 分类标题
            const sectionTitle = this.scene.add.text(centerX, currentY, title, {
                fontSize: isMobile ? '14px' : '18px',
                fill: color,
                fontStyle: 'bold',
                stroke: '#000000',
                strokeThickness: 2
            }).setOrigin(0.5).setScrollFactor(0).setDepth(2001);
            this.characterStatsElements.push(sectionTitle);
            currentY += 20;

            // 创建两列布局
            const leftColumn = centerX - (isMobile ? 120 : 150);
            const rightColumn = centerX + (isMobile ? 120 : 150);
            
            items.forEach((item, index) => {
                if (item.value === undefined || item.value === null) return;

                const column = index % 2 === 0 ? leftColumn : rightColumn;
                const y = currentY + Math.floor(index / 2) * lineHeight;
                
                let displayValue = item.value;
                if (item.type === 'percentage') {
                    displayValue = `${(item.value * 100).toFixed(1)}%`;
                } else if (item.type === 'decimal') {
                    displayValue = item.value.toFixed(2);
                } else if (item.type === 'integer') {
                    displayValue = Math.floor(item.value);
                }

                const statText = this.scene.add.text(column, y, `${item.label}: ${displayValue}`, {
                    fontSize: fontSize,
                    fill: '#ffffff',
                    stroke: '#000000',
                    strokeThickness: 1
                }).setOrigin(0.5, 0).setScrollFactor(0).setDepth(2001);
                this.characterStatsElements.push(statText);
            });

            currentY += Math.ceil(items.length / 2) * lineHeight + sectionSpacing;
        };

        // 核心属性
        createSection('核心属性', [
            { label: '生命值', value: `${stats.health} / ${stats.maxHealth}`, type: 'string' },
            { label: '法力值', value: `${stats.mana} / ${stats.maxMana}`, type: 'string' },
            { label: '能量值', value: `${stats.energy} / ${stats.maxEnergy}`, type: 'string' },
            { label: '当前等级', value: gameStats.level, type: 'integer' }
        ], '#00ffff');

        // 主要属性
        createSection('主要属性', [
            { label: '力量', value: stats.strength, type: 'integer' },
            { label: '敏捷', value: stats.agility, type: 'integer' },
            { label: '智力', value: stats.intelligence, type: 'integer' },
            { label: '体力', value: stats.vitality, type: 'integer' },
            { label: '幸运', value: stats.luck, type: 'integer' }
        ], '#ffff00');

        // 战斗属性
        createSection('战斗属性', [
            { label: '基础伤害', value: stats.damage, type: 'integer' },
            { label: '物理伤害', value: stats.physicalDamage, type: 'integer' },
            { label: '魔法伤害', value: stats.magicalDamage, type: 'integer' },
            { label: '真实伤害', value: stats.trueDamage, type: 'integer' },
            { label: '暴击率', value: stats.critChance, type: 'percentage' },
            { label: '暴击伤害', value: stats.critDamage, type: 'decimal' },
            { label: '攻击速度', value: stats.attackSpeed, type: 'decimal' },
            { label: '射速', value: `${(1000/stats.fireRate).toFixed(1)}/秒`, type: 'string' }
        ], '#ff9999');

        // 防御属性
        createSection('防御属性', [
            { label: '物理防御', value: stats.defense, type: 'integer' },
            { label: '魔法抗性', value: stats.magicResistance, type: 'integer' },
            { label: '护甲值', value: stats.armor, type: 'integer' },
            { label: '伤害减免', value: stats.damageReduction, type: 'percentage' },
            { label: '闪避率', value: stats.dodgeChance, type: 'percentage' },
            { label: '格挡率', value: stats.blockChance, type: 'percentage' },
            { label: '格挡值', value: stats.blockValue, type: 'integer' }
        ], '#99ff99');

        // 射击属性
        createSection('射击属性', [
            { label: '射程', value: stats.range, type: 'integer' },
            { label: '精准度', value: stats.accuracy, type: 'percentage' },
            { label: '穿透', value: stats.piercing, type: 'integer' },
            { label: '多重射击', value: stats.multishot, type: 'integer' },
            { label: '弹射次数', value: stats.ricochet, type: 'integer' },
            { label: '弹丸速度', value: stats.projectileSpeed, type: 'decimal' }
        ], '#ffaa99');

        // 恢复属性
        createSection('恢复属性', [
            { label: '生命回复', value: `${stats.healthRegen}/秒`, type: 'string' },
            { label: '法力回复', value: `${stats.manaRegen}/秒`, type: 'string' },
            { label: '能量回复', value: `${stats.energyRegen}/秒`, type: 'string' },
            { label: '生命偷取', value: stats.lifeSteal, type: 'percentage' },
            { label: '法力偷取', value: stats.manaSteal, type: 'percentage' }
        ], '#99ffff');

        // 移动属性
        createSection('移动属性', [
            { label: '移动速度', value: stats.speed, type: 'integer' },
            { label: '速度倍数', value: stats.moveSpeed, type: 'decimal' },
            { label: '冲刺速度', value: stats.sprintSpeed, type: 'decimal' },
            { label: '瞬移距离', value: stats.dashDistance, type: 'integer' }
        ], '#ff99ff');

        // 武器专精
        const masteryItems = [];
        if (stats.pistolMastery > 0) masteryItems.push({ label: '手枪专精', value: stats.pistolMastery, type: 'integer' });
        if (stats.shotgunMastery > 0) masteryItems.push({ label: '霰弹枪专精', value: stats.shotgunMastery, type: 'integer' });
        if (stats.rifleMastery > 0) masteryItems.push({ label: '步枪专精', value: stats.rifleMastery, type: 'integer' });
        if (stats.machinegunMastery > 0) masteryItems.push({ label: '机枪专精', value: stats.machinegunMastery, type: 'integer' });
        if (stats.laserMastery > 0) masteryItems.push({ label: '激光专精', value: stats.laserMastery, type: 'integer' });
        if (masteryItems.length > 0) {
            createSection('武器专精', masteryItems, '#ffcc99');
        }

        // 特殊属性
        const specialItems = [];
        if (stats.vampirism > 0) specialItems.push({ label: '吸血', value: stats.vampirism, type: 'percentage' });
        if (stats.berserker > 0) specialItems.push({ label: '狂暴', value: stats.berserker, type: 'percentage' });
        if (stats.focus > 0) specialItems.push({ label: '专注', value: stats.focus, type: 'percentage' });
        if (stats.combo > 0) specialItems.push({ label: '连击', value: stats.combo, type: 'integer' });
        if (stats.reviveChance > 0) specialItems.push({ label: '复活几率', value: stats.reviveChance, type: 'percentage' });
        if (stats.damageReflection > 0) specialItems.push({ label: '伤害反射', value: stats.damageReflection, type: 'percentage' });
        if (specialItems.length > 0) {
            createSection('特殊属性', specialItems, '#cc99ff');
        }

        // 游戏统计
        createSection('游戏统计', [
            { label: '当前波次', value: gameStats.wave, type: 'integer' },
            { label: '击杀敌人', value: gameStats.enemiesKilled, type: 'integer' },
            { label: '击杀Boss', value: gameStats.bossesKilled, type: 'integer' },
            { label: '获得金币', value: gameStats.gold, type: 'integer' },
            { label: '游戏时间', value: `${Math.floor(gameStats.gameTime / 60)}:${(gameStats.gameTime % 60).toString().padStart(2, '0')}`, type: 'string' },
            { label: '升级次数', value: gameStats.upgradeCount, type: 'integer' }
        ], '#ffd700');

        // 成就信息
        const achievementY = centerY + (isMobile ? 60 : 80);
        const achievementTitleSize = isMobile ? '16px' : '20px';
        const achievementTitle = this.scene.add.text(centerX, achievementY, '成就进度', {
            fontSize: achievementTitleSize,
            fill: '#ffd700',
            fontStyle: 'bold',
            stroke: '#000000',
            strokeThickness: 2
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2001);

        // 获取成就系统的进度
        let achievementProgress = '';
        if (this.scene.achievementSystem && this.scene.achievementSystem.achievements) {
            const achievements = this.scene.achievementSystem.achievements;
            if (Array.isArray(achievements)) {
                const completed = achievements.filter(a => a && a.completed).length;
                achievementProgress = `已完成: ${completed} / ${achievements.length}`;
            } else {
                achievementProgress = '成就数据加载中...';
            }
        } else {
            achievementProgress = '成就系统未初始化';
        }

        const achievementTextSize = isMobile ? '12px' : '16px';
        const achievementText = this.scene.add.text(centerX, achievementY + 25, achievementProgress, {
            fontSize: achievementTextSize,
            fill: '#ffd700',
            stroke: '#000000',
            strokeThickness: 1
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2001);

        // 按钮区域
        const buttonY = centerY + panelHeight / 2 - 80;
        const buttonSpacing = isMobile ? 80 : 120;

        // 继续游戏按钮
        const continueButton = this.scene.add.rectangle(centerX - buttonSpacing/2, buttonY, isMobile ? 100 : 120, isMobile ? 35 : 40, 0x27ae60, 0.8)
            .setScrollFactor(0)
            .setDepth(2001)
            .setInteractive({ useHandCursor: true });

        const continueText = this.scene.add.text(centerX - buttonSpacing/2, buttonY, '继续游戏', {
            fontSize: isMobile ? '12px' : '16px',
            fill: '#ffffff',
            fontStyle: 'bold'
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2002);

        // 结束游戏按钮
        const endButton = this.scene.add.rectangle(centerX + buttonSpacing/2, buttonY, isMobile ? 100 : 120, isMobile ? 35 : 40, 0xe74c3c, 0.8)
            .setScrollFactor(0)
            .setDepth(2001)
            .setInteractive({ useHandCursor: true });

        const endText = this.scene.add.text(centerX + buttonSpacing/2, buttonY, '结束游戏', {
            fontSize: isMobile ? '12px' : '16px',
            fill: '#ffffff',
            fontStyle: 'bold'
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2002);

        // 按钮事件
        continueButton.on('pointerdown', () => {
            this.scene.togglePause(); // 继续游戏
        });

        endButton.on('pointerdown', () => {
            // 结束游戏，显示游戏结束界面
            this.hideCharacterStats();
            this.scene.isManuallyPaused = false;
            this.showGameOver({
                wave: this.scene.wave,
                enemiesKilled: this.scene.enemiesKilled,
                bossesKilled: this.scene.bossesKilled,
                gameTime: this.scene.gameTime
            });
        });

        // 按钮悬停效果
        [continueButton, endButton].forEach(button => {
            button.on('pointerover', () => {
                button.setScale(1.05);
            });

            button.on('pointerout', () => {
                button.setScale(1.0);
            });
        });

        // 提示文本
        const hintTextSize = isMobile ? '12px' : '14px';
        const hintMessage = isMobile ? '选择操作' : '按 ESC 键继续游戏';
        const hintText = this.scene.add.text(centerX, buttonY + 50, hintMessage, {
            fontSize: hintTextSize,
            fill: '#888888',
            stroke: '#000000',
            strokeThickness: 1
        }).setOrigin(0.5).setScrollFactor(0).setDepth(2001);

        // 保存引用 - 将所有元素加入清理列表
        this.characterStatsPanel = background;
        this.characterStatsElements.push(
            background, title, achievementTitle, achievementText,
            continueButton, continueText, endButton, endText, hintText
        );
    }

    // 隐藏角色属性面板
    hideCharacterStats() {
        // 清理所有元素，包括背景
        this.characterStatsElements.forEach(element => {
            if (element && element.destroy) {
                element.destroy();
            }
        });
        this.characterStatsElements = [];

        // 重置面板引用
        this.characterStatsPanel = null;
    }
}
